package org.mclll.xwangplugin.town.listener;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.mclll.xwangplugin.MclllCustom;
import org.mclll.xwangplugin.log.GlobalLog;
import org.mclll.xwangplugin.log.LogUtil;
import org.mclll.xwangplugin.log.LoggerFactory;
import org.mclll.xwangplugin.town.database.domain.TownPlayerDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownPlayerManage;
import org.mclll.xwangplugin.town.enums.PlayerTownIdentity;

import static org.mclll.xwangplugin.town.command.executor.InvitePlayerExecutor.sendInviteMessage;

/**
 * @author: geduo
 * @date: 2023/9/19 16:51
 */
public class PlayerListener implements Listener {
    private final MclllCustom plugin;
    private LogUtil log;
    private static Boolean firstJoin = true;

    public PlayerListener(MclllCustom plugin) {
        this.plugin = plugin;
        log = LoggerFactory.get(GlobalLog.class);
    }

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onPlayerJoin(PlayerJoinEvent event) {
        // 第一个玩家加入服务器执行
        if (firstJoin) {
            firstJoin = false;
            Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "cc reload");
            log.info("CC reloading................");
        }
        Player player = event.getPlayer();
        String uuid = player.getUniqueId().toString();
        TownPlayerDO townPlayer = TownPlayerManage.selectByUuid(uuid);
        if (townPlayer == null) {
            TownPlayerDO townPlayerDO = new TownPlayerDO();
            townPlayerDO.setUuid(player.getUniqueId().toString());
            townPlayerDO.setIdentity(PlayerTownIdentity.GENSHIN);
            townPlayerDO.setName(player.getName());
            TownPlayerManage.insert(townPlayerDO);
        }
        sendInviteMessage(player, null);
    }
}
